﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Com.Alipay;
using System.Collections.Specialized;
using Maticsoft.Common;

namespace Maticsoft.Web.wap.pay.alipay
{
    public partial class notify_url : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            SortedDictionary<string, string> sPara = GetRequestPost();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify aliNotify = new Notify();
                bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"]);

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


                    //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                    //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

                    //商户订单号

                    string out_trade_no = Request.Form["out_trade_no"];

                    //支付宝交易号

                    string trade_no = Request.Form["trade_no"];

                    //交易状态
                    string trade_status = Request.Form["trade_status"];


                    if (Request.Form["trade_status"] == "TRADE_FINISHED")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                        //如果有做过处理，不执行商户的业务程序

                        //注意：
                        //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    }
                    else if (Request.Form["trade_status"] == "TRADE_SUCCESS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                        //如果有做过处理，不执行商户的业务程序

                        //注意：
                        //付款完成后，支付宝系统发送该交易状态通知
                        string[] arr = out_trade_no.Split('|');
                        foreach (string s in arr)
                        {
                            BLL.Orders orderBLL = new BLL.Orders();
                            Model.Orders orderModel = orderBLL.GetModel(DigitHelper.GetInt32(s));
                            if (orderModel != null)
                            {
                                //更新订单状态
                                orderModel.Status = 2;
                                orderModel.PayTime = DateTime.Now;
                                orderModel.UpdateTime = DateTime.Now;
                                orderModel.TradeNo = trade_no;
                                orderBLL.Update(orderModel);
                                //修改库存
                                BLL.Oitems oitemBLL = new BLL.Oitems();
                                BLL.Products proBLL = new BLL.Products();
                                Model.Products proModel = null;
                                List<Model.Oitems> list = oitemBLL.GetModelList("OrderId=" + s);
                                foreach (Model.Oitems o in list)
                                {
                                    proModel = proBLL.GetModel((int)o.ProductId);
                                    proModel.StoreNum = proModel.StoreNum - o.ProductNum;
                                    proModel.UpdateTime = DateTime.Now;
                                    proBLL.Update(proModel);
                                }
                                //添加积分记录
                                BLL.CreditHistory chBLL = new BLL.CreditHistory();
                                Model.CreditHistory chModel = new Model.CreditHistory();
                                chModel.CreateTime = DateTime.Now;
                                chModel.IsActive = 1;
                                chModel.SourceId = 1;
                                chModel.Type = 1;
                                chModel.UpdateTime = DateTime.Now;
                                chModel.UserId = orderModel.UserId;
                                chModel.Val = (int)orderModel.Total;
                                chBLL.Add(chModel);
                                //修改会员总积分
                                BLL.Members meBLL = new BLL.Members();
                                Model.Members meModel = meBLL.GetModel((int)orderModel.UserId);
                                meModel.Credits = DigitHelper.GetInt32(meModel.Credits) + (int)orderModel.Total;
                                meModel.UpdateTime = DateTime.Now;
                                meBLL.Update(meModel);
                            }
                        }
                    }
                    else
                    {
                    }

                    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                    Response.Write("success");  //请不要修改或删除

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    Response.Write("fail");
                }
            }
            else
            {
                Response.Write("无通知参数");
            }
        }

        /// <summary>
        /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestPost( )
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }

            return sArray;
        }
    }
}